import { Cascader, Checkbox, Input, message, Tooltip } from 'antd';
import React, { useEffect, useState } from 'react';
import Space from '@/components/Space';

function findMatchedOptionValues(options, value) {
  const matchedValues = [];
  let current = options;
  // eslint-disable-next-line no-restricted-syntax
  for (const name of value) {
    const found = current.find(each => each.label === name);
    if (!found) {
      return [];
    }
    matchedValues.push(found.value);
    current = found.children;
  }
  return matchedValues;
}

function CatalogSelector({ value = [], options = [], onChange }) {
  const matchedValues = findMatchedOptionValues(options, value);
  const [manually, setManually] = useState(matchedValues.length === 0);
  const [inputValue, setInputValue] = useState(value.join('/'));

  useEffect(() => {
    setInputValue(value.join('/'));
  }, [value]);

  function handleInputBlur(inputValue) {
    const catalogNames = inputValue.split('/');
    const hasEmptyName = catalogNames.some(name => {
      if (name === '') {
        return true;
      }
      if (name.startsWith(' ') || name.endsWith(' ')) {
        return true;
      }
      return false;
    });
    if (hasEmptyName) {
      message.error('目录路径不能存在空字符串或者前后空白');
      onChange(value);
      return;
    }
    onChange(catalogNames);
  }

  const prefix = manually ? (
    <Input
      onBlur={e => handleInputBlur(e.target.value)}
      style={{ width: '200px' }}
      value={inputValue}
      onChange={e => setInputValue(e.target.value)}
      placeholder="请输入目录路径，如：a/b/c"
    />
  ) : (
    <Cascader
      style={{ width: '200px' }}
      placeholder="--请选择--"
      allowClear={false}
      changeOnSelect
      expandTrigger="hover"
      options={options}
      value={matchedValues}
      onChange={(_value, options) => {
        onChange && onChange(options.map(options => options.label));
      }}
    />
  );

  return (
    <Space>
      {prefix}
      <Tooltip title="是否手动创建目录">
        <Checkbox checked={manually} onChange={e => setManually(e.target.checked)} />
      </Tooltip>
    </Space>
  );
}

export default CatalogSelector;
